﻿using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace App_1.Identity
{
    public class IdentityService : IIdentityService
    {
        private readonly IOptions<JwtSettings> _jwtSettings;
        public IdentityService(IOptions<JwtSettings> jwtSettings)
        {
            _jwtSettings = jwtSettings;
        }

        public string? GetAccessToken(IdentityUser user)
        {
            // 创建 JWT
            var jwt = new JwtSecurityToken(
                _jwtSettings.Value.Issuer,
                _jwtSettings.Value.Audience,
                new[] //声明
                {
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(ClaimTypes.Name, user.UserName!)
                },
                expires: DateTime.Now.AddMinutes(_jwtSettings.Value.AccessTokenExpirationMinutes), //过期时间
                signingCredentials: new SigningCredentials( //签名凭据对象
                    new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.Value.Secret!)),//密钥
                    SecurityAlgorithms.HmacSha256)//加密方式
            );

            // 生成 JWT 字符串
            var token = new JwtSecurityTokenHandler().WriteToken(jwt);
            return token;
        }
    }
}
